package net.csdn.business.notify.handler.action;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.enums.NotifyChannel;
import net.csdn.business.notify.common.enums.NotifyType;
import net.csdn.business.notify.common.model.entity.NotifyPrivateLetter;
import net.csdn.business.notify.common.model.entity.NotifyRemindRecord;
import net.csdn.business.notify.common.model.vo.UserInfoVO;
import net.csdn.business.notify.common.pipeline.BusinessProcess;
import net.csdn.business.notify.common.pipeline.ProcessContext;
import net.csdn.business.notify.common.pipeline.domain.TaskInfo;
import net.csdn.business.notify.handler.service.INotifyPrivateLetterService;
import net.csdn.business.notify.handler.service.INotifyRemindRecordService;
import net.csdn.business.notify.common.utils.StrUtils;
import net.csdn.business.notify.feign.SystemFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @ClassName SaveRemindAction
 * @Description 记录通知记录，并根据用户id转换用户账号信息
 * @Author zhangyl
 * @Date 2023/11/30 17:03
 */
@Slf4j
@Service
public class SaveRemindAction implements BusinessProcess<TaskInfo> {


    @Autowired
    private SystemFeignClient userFeignClient;

    @Autowired
    private INotifyRemindRecordService remindRecordService;
    @Autowired
    private INotifyPrivateLetterService privateLetterService;

    @Override
    public void process(ProcessContext<TaskInfo> context) {

        TaskInfo taskInfo = context.getProcessModel();
        List<String> receiversBefore=new ArrayList<>(taskInfo.getReceiver());
        Integer notifyChannel=taskInfo.getNotifyChannel();
        Integer notifyType=taskInfo.getNotifyType();
        Integer notifyState=0;
        //站内信的投递状态直接设置为投递成功。
        if(NotifyChannel.IM.getCode().equals(notifyChannel)){
            notifyState=1;
        }
        String targetType=taskInfo.getTargetType();
        String senderId=taskInfo.getSenderId();
        String act=taskInfo.getAct();
        JSONObject contentJson=JSON.parseObject(taskInfo.getContentModel());
        String content=contentJson.getString("content");
        String batchNum=taskInfo.getBatchNum();

        //批量查询用户信息，并记录到数据库
        if (receiversBefore!=null&&receiversBefore.size()>0){
            //防止查询数据过多，分批查询
            List<String> receiversAccount=new ArrayList<>();
            List<List<String>> uidBathList= Lists.partition(receiversBefore, 50);
            for (List<String> userIdList:uidBathList){
                if(notifyType.equals(NotifyType.REMIND.getCode())){
                    Map<String, UserInfoVO> userinfos=null;
                    if(notifyChannel.equals(NotifyChannel.EMAIL.getCode())){
                        //批量查询用户信息配置信息
                        try{
                            userinfos=userFeignClient.batchQuery(userIdList);
                        }catch (Exception e){
                            log.info("userFeignClient batchQuery error:{}",e.getMessage());
                        }
                        //证明传入的用户id都无效，直接跳过，进行下一批次用户查询
                       /* if(userinfos==null||userinfos.size()==0){
                            continue;
                        }*/
                    }
                    //批量入库当前批次通知记录
                    List<NotifyRemindRecord> records=new ArrayList<>();
                    for (String userId:userIdList){
                        if(StringUtils.isBlank(userId)||userId.equals(senderId)){
                            continue;
                        }
                        String receiverAcount=null;
                        NotifyRemindRecord remindRecord=new NotifyRemindRecord();
                        remindRecord.setNotifyState(0);
                        if(notifyChannel.equals(NotifyChannel.EMAIL.getCode())){
                            UserInfoVO userInfoVO=userinfos!=null?userinfos.get(userId):null;
                            if(userInfoVO!=null){
                                receiverAcount=userInfoVO.getEmail();
                                receiversAccount.add(receiverAcount);
                                remindRecord.setReceiverAccount(receiverAcount);
                            }else{
                                //账号不存在，则修改状态为投递失败
                                remindRecord.setNotifyState(-1);
                            }
                        }
                        //当用户存在时,组装用户通知记录信息，批量保存入库
                        BeanUtils.copyProperties(taskInfo,remindRecord);
                        remindRecord.setObjectId(IdUtil.fastSimpleUUID());
                        remindRecord.setReceiverId(userId);
                        remindRecord.setContent(content);
                        remindRecord.setReadState(0);
                        remindRecord.setNotifyState(notifyState);
                        remindRecord.setCreatedDate(taskInfo.getSendDate());
                        remindRecord.setNotifyType(notifyType);
                        records.add(remindRecord);
                    }
                    if(records.size()>0){
                        //此处后面可以改为异步
                        remindRecordService.insertBatch(records);
                    }
                }else{
                    //站内信渠道批量入库当前批次通知记录
                    if(notifyChannel.equals(NotifyChannel.IM.getCode())){
                        List<NotifyPrivateLetter> records=new ArrayList<>();
                        for (String receiverId:userIdList){
                            if(StringUtils.isBlank(receiverId)||receiverId.equals(senderId)){
                                continue;
                            }
                            NotifyPrivateLetter privateLetter=new NotifyPrivateLetter();
                            privateLetter.setObjectId(IdUtil.fastSimpleUUID());
                            privateLetter.setReceiverId(receiverId);
                            privateLetter.setBatchNum(batchNum);
                            String dialogueId= StrUtils.genDialogueId(senderId,receiverId);
                            privateLetter.setDialogueId(dialogueId);
                            privateLetter.setContent(content);
                            privateLetter.setCreatedDate(taskInfo.getSendDate());
                            privateLetter.setSenderId(senderId);
                            privateLetter.setIsSystem(true);
                            records.add(privateLetter);
                        }
                        if(records.size()>0){
                            //此处后面可以改为异步
                            privateLetterService.insertBatch(records);
                        }
                    }else{
                        //私信类型的邮件通知渠道
                        Map<String, UserInfoVO> userinfos=null;
                        try{
                            userinfos=userFeignClient.batchQuery(userIdList);
                        }catch (Exception e){
                            log.info("userFeignClient batchQuery error:{}",e.getMessage());
                        }
                        //批量入库当前批次通知记录
                        List<NotifyRemindRecord> records=new ArrayList<>();
                        for (String userId:userIdList){
                            if(StringUtils.isBlank(userId)||userId.equals(senderId)){
                                continue;
                            }
                            String receiverAcount=null;
                            NotifyRemindRecord remindRecord=new NotifyRemindRecord();
                            if(notifyChannel.equals(NotifyChannel.EMAIL.getCode())){
                                UserInfoVO userInfoVO=userinfos!=null?userinfos.get(userId):null;
                                if(userInfoVO!=null){
                                    receiverAcount=userInfoVO.getEmail();
                                    receiversAccount.add(receiverAcount);
                                    remindRecord.setReceiverAccount(receiverAcount);
                                }else{
                                    //账号不存在，则修改状态为投递失败
                                    remindRecord.setNotifyState(-1);
                                }
                            }
                            //当用户存在时,组装用户通知记录信息，批量保存入库
                            BeanUtils.copyProperties(taskInfo,remindRecord);
                            remindRecord.setObjectId(IdUtil.fastSimpleUUID());
                            remindRecord.setReceiverId(userId);
                            remindRecord.setContent(content);
                            remindRecord.setReadState(0);
                            remindRecord.setNotifyType(notifyType);
                            remindRecord.setNotifyState(notifyState);
                            remindRecord.setCreatedDate(taskInfo.getSendDate());
                            records.add(remindRecord);
                        }
                        if(records.size()>0){
                            //此处后面可以改为异步
                            try {
                                remindRecordService.insertBatch(records);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            if(notifyChannel.equals(NotifyChannel.EMAIL.getCode())&&receiversAccount.size()==0){
                //如果邮件接收账号为空，则终止流程
                context.setNeedBreak(true);
            }
            taskInfo.setAccounts(receiversAccount);
        }
    }
}
